package org.smart.framework.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by IntelliJ IDEA.
 *
 * @Auther Uncle_Z
 * @date 2017/8/23 15:53
 * @Email:2545375@qq.com
 * @since 1.0
 * To change this template use File | Settings | File Templates.
 */

public final class ReflectionUtil {

    private static final Logger LOGGER = LogManager.getLogger(ReflectionUtil.class);


    /**
     * 创建实例
     * @param cls
     * @return
     */
    public static Object newInstance(Class<?> cls) {
        Object instance;
        try {
            instance = cls.newInstance();
        } catch (Exception e) {
            LOGGER.error("new Instance failure", e);
            throw new RuntimeException(e);
        }
        return instance;
    }


    /**
     * 调用方法
     * @param obj
     * @param method
     * @param args
     * @return
     */
    public static Object invokeMethod(Object obj, Method method, Object... args) {
        Object result;
        try {
            method.setAccessible(true);
            result = method.invoke(obj, args);
        } catch (Exception e) {
            LOGGER.error("invoke method failure", e);
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 设置成员变量值
     * @param obj
     * @param field
     * @param value
     */
    public static void setField(Object obj, Field field, Object value) {
        try {
            field.setAccessible(true);
            field.set(obj, value);
        } catch (Exception e) {
            LOGGER.error("set file failure", e);
            throw new RuntimeException(e);
        }
    }
}
